package usersManagement.security;

import javax.annotation.PostConstruct;
import javax.enterprise.inject.Produces;
import javax.inject.Inject;
import javax.inject.Named;
import javax.inject.Singleton;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.mgt.SecurityManager;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import usersManagement.model.User;
import usersManagement.service.UserService;
import usersManagement.util.AppLog;

/**
 * @author Edward P. Legaspi
 * @since Oct 10, 2012 Produces an instance of Shiro's subject so that it can be
 *        injected.
 */
@Singleton
public class SecurityProducer {

    @Inject @AppLog private Logger log;
    @Inject private UserService userService ;
    private SecurityManager securityManager;

    @PostConstruct
    public void init() {
        final String iniFile = "classpath:shiro.ini";
        log.info("Initializing Shiro INI SecurityManager using " + iniFile);
        securityManager = new IniSecurityManagerFactory(iniFile).getInstance();
        SecurityUtils.setSecurityManager(securityManager);
    }

    @Produces
    @Named("securityManager")
    public SecurityManager getSecurityManager() {
        return securityManager;
    }

    @Produces
    @Named("loggedSubject")
    public Subject getLoggedSubject() {
        return SecurityUtils.getSubject();
    }

    @Produces
    @LoggedUser
    @Named("loggedUser")
    public User getLoggedUser() {
        return userService.findByUsername((String)SecurityUtils.getSubject().getPrincipal());
    }
}